package jml.plugins.mostplayed;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import jml.def.Label;
import jml.def.Library;
import jml.def.Plugin;
import jml.def.Title;
import jml.defaultimple.util.UDate;
import jml.defaultimple.util.UString;

public class MostPlayed extends Plugin
{
	private final String COOKIE_fAdded = "fAdded";
	private final String COOKIE_nClicks = "nClicks";
	
	private ArrayList<Title> titulos = null;
	
	public MostPlayed()
	{
		titulos = new ArrayList<Title>();
	}
	
	@Override
	public void onLoad(Title t)
	{
		
		String clicks = t.loadPrivateCookie(COOKIE_nClicks,getClass());
		if( clicks == null)
		{
			clicks = "0";
			t.storePrivateCookie(COOKIE_nClicks, "0",getClass());
		}

		int n = Integer.parseInt(clicks);
		
		if( n>0 )
		{
			titulos.add(t);
		}
	}

	@Override
	public void onPlay(Title t)
	{
		int n = Integer.parseInt(t.loadPrivateCookie(COOKIE_nClicks,getClass()));
		
		// incremento el contador
		t.storePrivateCookie(COOKIE_nClicks, Integer.toString(n+1),getClass());
		
		// almaceno la fecha del ultima reproduccion
		t.storePrivateCookie(COOKIE_fAdded, UDate.nowTime(), getClass());
	}

	@Override
	public void onEdit(Title t)
	{
		// TODO Auto-generated method stub
	}

	@Override
	public void onRefresh(Library t)
	{
	}

	@Override
	public void onOpenLabel(String filter, String label)
	{
	}

	@Override
	public void beforeLoading(Library lib)
	{
		titulos.clear();
	}

	@Override
	public void afterLoading(Library lib)
	{
		// ordeno
		Collections.sort(titulos,new Ordenar());
		
		// armo la lista
		Label lbl = getPluginLabel();
		lbl.getTitles().clear();
		
		int nDiscs = Integer.parseInt(getParameters().get("nDiscs"));
		for(int i=0; i<nDiscs && i<titulos.size(); i++)
		{
			lbl.getTitles().add(i, titulos.get(i));
		}
		
		titulos.clear();	
	}
	
	class Ordenar implements Comparator<Title>
	{
		@Override
		public int compare(Title o1, Title o2)
		{
			String sN1 = UString.lpad(o1.loadPrivateCookie(COOKIE_nClicks,MostPlayed.class), '0', 30);
			String sN2 = UString.lpad(o2.loadPrivateCookie(COOKIE_nClicks,MostPlayed.class), '0', 30);

			String f1 = o1.loadPrivateCookie(COOKIE_fAdded,MostPlayed.class);
			String f2 = o2.loadPrivateCookie(COOKIE_fAdded,MostPlayed.class);

			String s1 = sN1+"_"+f1;
			String s2 = sN2+"_"+f2;
			
			return -1*s1.compareTo(s2);
		}
	}
}
